package com.kt.learn1

/**
 * Kotlin 面向对象编程示例
 * 包括类与对象、属性与方法、继承与多态、抽象类与接口
 */

fun main() {
    // 类与对象
    chapter1ClassesAndObjects()

    // 属性与方法
    chapter2PropertiesAndMethods()

    // 继承与多态
    chapter3InheritanceAndPolymorphism()

    // 抽象类与接口
    chapter4AbstractClassesAndInterfaces()
}

// 类与对象
fun chapter1ClassesAndObjects() {
    println("\n===== 类与对象 =====")

    // 声明一个简单的类
    class Person(val name: String, var age: Int) {
        // 成员函数
        fun introduce() {
            println("My name is $name and I'm $age years old.")
        }
    }

    // 创建对象
    val person = Person("Alice", 25)
    person.introduce() // 输出：My name is Alice and I'm 25 years old.
}

// 属性与方法
fun chapter2PropertiesAndMethods() {
    println("\n===== 属性与方法 =====")

    // 声明一个带有属性和方法的类
    class Car(val brand: String, var model: String, var year: Int) {
        // 属性
        var color: String = "Unknown"

        // 方法
        fun displayInfo() {
            println("Brand: $brand, Model: $model, Year: $year, Color: $color")
        }

        // 初始化块
        init {
            println("A new Car object is created.")
        }
    }

    // 创建对象并访问属性和方法
    val car = Car("Toyota", "Camry", 2020)
    car.color = "Red"
    car.displayInfo()
    // 输出：
    // A new Car object is created.
    // Brand: Toyota, Model: Camry, Year: 2020, Color: Red
}

// 继承与多态
fun chapter3InheritanceAndPolymorphism() {
    println("\n===== 继承与多态 =====")

    // 声明一个基类
    open class Animal(val species: String) {
        open fun makeSound() {
            println("Some sound")
        }
    }

    // 声明一个派生类
    class Dog(species: String) : Animal(species) {
        override fun makeSound() {
            println("Woof!")
        }
    }

    // 多态示例
    fun animalSound(animal: Animal) {
        animal.makeSound()
    }

    val dog = Dog("Golden Retriever")
    animalSound(dog) // 输出：Woof!
}

// 抽象类与接口
fun chapter4AbstractClassesAndInterfaces() {
    println("\n===== 抽象类与接口 =====")

    // 抽象类
    abstract class Shape(val name: String) {
        abstract fun area(): Double
        open fun display() {
            println("Shape: $name")
        }
    }


    // 实现抽象类和接口
    class Circle(name: String, val radius: Double) : Shape(name), Drawable {
        override fun area(): Double {
            return Math.PI * radius * radius
        }

        override fun draw() {
            println("Drawing a circle with radius $radius")
        }

        override fun display() {
            super.display()
            println("Area: ${area()}")
        }
    }

    val circle = Circle("Circle", 5.0)
    circle.display()
    circle.draw()
    // 输出：
    // Shape: Circle
    // Area: 78.53981633974483
    // Drawing a circle with radius 5.0
}